﻿using System.Collections.Generic;
using System.Linq;
using DMS.Filters;
using DMS.Mappers;
using System;
using DMS.BEs;
using DMS.DTOs;
using DMS.Models;

namespace DMS.Services.Impl
{
    public class InvoiceViewServiceImpl : ServiceModelBase<IInvoiceViewModel>, IInvoiceViewService
    {
    	public InvoiceViewServiceImpl(IInvoiceViewModel model, IMapperBEtoDTO mapperBEtoDTO)
    		: base(model, mapperBEtoDTO)
    	{}

        public ResultDTO<InvoiceWithLinesDTO> GetInvoiceById(int invoiceId)
        {
            Invoice invoice;
            try
            {
                invoice = model.GetInvoiceById(invoiceId);
            }
            catch (Exception exception)
            {
                ResultDTO<InvoiceWithLinesDTO> result = new ResultDTO<InvoiceWithLinesDTO>(null);
                result.Exception = exception;
                return result;
            }

            InvoiceWithLinesDTO dto = mapperBEtoDTO.Map<Invoice, InvoiceWithLinesDTO>(invoice);
            return new ResultDTO<InvoiceWithLinesDTO>(dto);
        }

        public ResultListDTO<InvoiceDTO> GetInvoicesByContry(string country)
        {
            IList<Invoice> invoices;
            try
            {
                invoices = model.GetInvoicesByFilter(new InvoiceFilter() {Country = country});
            }
            catch (Exception exception)
            {
                ResultListDTO<InvoiceDTO> result = new ResultListDTO<InvoiceDTO>(null);
                result.Exception = exception;
                return result;
            }

            IEnumerable<InvoiceDTO> items = (from i in invoices select mapperBEtoDTO.Map<Invoice, InvoiceDTO>(i));
            return new ResultListDTO<InvoiceDTO>(items.ToArray());
        }
    }
}
